﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Common.Model;
using Yipusoft.Task.BLL;
using Yipusoft.Task.Model;
using Yipusoft.Evaluate.BLL;
using Yipusoft.Evaluate.Model;
using System.Collections.Generic;
using System.Text;

public partial class Evaluate_TaskEvaluateDetachment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, "320101"))
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
        }
        if (!IsPostBack)
        {
            init();
        }
    }

    public void init()
    {
        TaskInfo task = Task.GetTask(int.Parse(Request.QueryString["RootId"]));
        if (task.CreateDepartment != Session["DepartmentID"].ToString())
        {
            Response.Write("<script>alert('非任务所有者，无权操作！');history.back(0);</script>");
        }
        TaskTitle.Text = task.Title;
        TaskDate.Text = task.StartDate.ToShortDateString() + " - " + task.EndDate.ToShortDateString();
        hidDate.Value = task.EndDate.ToShortDateString();
        UserName.Text = Department.GetDepartment(Request.QueryString["UserID"]).FullName;
        BindData();
    }

    private void BindData()
    {
        //任务分数及完成率
        TaskInfo root = Task.GetTask(int.Parse(Request.QueryString["RootId"]));
        TaskUserInfo user = TaskUser.GetTaskUser(int.Parse(Request.QueryString["RootId"]), Request.QueryString["UserID"]);
        InitScore.Text = root.InitScore.ToString();
        Progress.Text = user.Progress.ToString() + "%";
        if (user.Progress == 0)
        {
            lblScore.Text = "0";
        }
        else
        {
            lblScore.Text = Convert.ToDecimal(root.InitScore * user.Progress / 100).ToString("##.##");
        }

        //任务明细
        TaskLogInfo log;
        string[] CnNums = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
        StringBuilder sb = new StringBuilder();
        List<TaskInfo> tasks = Task.GetTasks(int.Parse(Request.QueryString["RootId"]));
        sb.Append("<div class=title>" + tasks[0].Title + "</div>");
        sb.Append("<div class=date>" + Department.GetDepartment(Request.QueryString["UserID"]).FullName + " ");
        sb.Append("[" + tasks[0].StartDate.ToShortDateString() + "—" + tasks[0].EndDate.ToShortDateString() + "] ");
        sb.Append("实得分：" + user.Score.ToString() + " ");

        if (user.Score > 0)
            lblScore.Text = user.Score.ToString("0.00");
        else
            lblScore.Text = "0";
        if (user.Evaluated)
        {
            sb.Append("<img src=../images/icon_evaluated.gif align=absMiddle>");
        }
        else
        {
            sb.Append("<img src=../images/icon_unevaluated.gif align=absMiddle>");
        }
        sb.Append("</div>");
        if (tasks[0].Comment != "")
        {
            sb.Append("<div class=comment>" + UserFun.TextToHtml(tasks[0].Comment) + "</div>");
        }
        //显示附件
        if (tasks[0].Files.Count > 0)
        {
            foreach (TaskFileInfo file in tasks[0].Files)
            {
                sb.Append("<div class=file><img src=../images/attachment.gif alt=> <a href=../Upload" + file.FileName + " target=_blank>" + file.FileTitle + "</a></div>");
            }
        }
        log = TaskLog.GetTaskLog(tasks[0].TaskId, Request.QueryString["UserID"]);
        if (log != null)
        {
            sb.Append("<div class=report>" + UserFun.TextToHtml(log.Comment) + "<br>");
            //显示附件
            if (log.Files.Count > 0)
            {
                foreach (TaskLogFileInfo file in log.Files)
                {
                    sb.Append("<div class=file><img src=../images/attachment.gif alt=><a href=../Upload" + file.FileName + " target=_blank>" + file.FileTitle + "</a></div>");
                }
            }
            sb.Append("<div class=remark>完成进度：" + log.Progress.ToString() + "%<br>汇报单位：" + log.UpdateDepartment + "<br>汇 报 人：" + log.UpdateUser + "<br>汇报时间：" + log.CreateDate.ToString() + "</div></div>");
        }
        int j = 0;
        int k = 1;
        for (int i = 1; i < tasks.Count; i++)
        {
            TaskInfo task = tasks[i];
            if (task.Depth == 1)
            {
                sb.Append("<div class=subtitle>");
                sb.Append("第" + CnNums[j] + "阶段、");
                j++;
                k = 1;
            }
            else
            {
                sb.Append("<div class=thtitle>");
                sb.Append(k.ToString() + "、");
                k++;
            }
            sb.Append(task.Title + "[" + task.StartDate.ToString("MM-dd") + "—" + task.EndDate.ToString("MM-dd") + "]");
            sb.Append("</div>");
            if (tasks[i].Comment != "")
            {
                sb.Append("<div class=comment>" + UserFun.TextToHtml(task.Comment) + "</div>");
            }
            //显示附件
            if (task.Files.Count > 0)
            {
                foreach (TaskFileInfo file in task.Files)
                {
                    sb.Append("<div class=file><img src=../images/attachment.gif alt=> <a href=../Upload" + file.FileName + " target=_blank>" + file.FileTitle + "</a></div>");
                }
            }
            log = TaskLog.GetTaskLog(task.TaskId, Request.QueryString["UserID"]);
            if (log != null)
            {
                sb.Append("<div class=report>" + UserFun.TextToHtml(log.Comment) + "<br>");
                //显示附件
                if (log.Files.Count > 0)
                {
                    foreach (TaskLogFileInfo file in log.Files)
                    {
                        sb.Append("<div class=file><img src=../images/attachment.gif alt=><a href=../Upload" + file.FileName + " target=_blank>" + file.FileTitle + "</a></div>");
                    }
                }
                sb.Append("<div class=remark>完成进度：" + log.Progress.ToString() + "%<br>汇报单位：" + log.UpdateDepartment + "<br>汇 报 人：" + log.UpdateUser + "<br>汇报时间：" + log.CreateDate.ToString() + "</div></div>");
            }
        }

        Body.Text = sb.ToString();
        string where = "taskId=" + user.TaskId + " and Userid='" + user.UserId + "' ";
        List<TaskReasonInfo> list = Yipusoft.Task.BLL.TaskReasons.GetList(where);
        gvReason.DataSource = list;
        gvReason.DataBind();

    }
    public string GetUserName(string userId)
    {
        return Department.GetDepartment(userId).ShortName;
    }
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        int TaskId = int.Parse(Request.QueryString["RootId"]);
        string Userid = Request.QueryString["UserID"];
        string where = "taskId=" + TaskId + " and Userid='" + Userid + "' ";
        List<TaskReasonInfo> list = Yipusoft.Task.BLL.TaskReasons.GetList(where);

        TaskInfo root = Task.GetTask(int.Parse(Request.QueryString["RootId"]));
        TaskUserInfo user = TaskUser.GetTaskUser(int.Parse(Request.QueryString["RootId"]), Request.QueryString["UserID"]);

        decimal point = Convert.ToDecimal(txtPoint.Text);
        decimal TotolScore = Convert.ToDecimal(root.InitScore * user.Progress / 100);

        if (TotolScore - point < 0)
        {
            Prompt.Text = "提示：任务得分不可以为负！";
            return;
        }

        TaskReasonInfo info = new TaskReasonInfo();
        info.UserId = Userid;
        info.TaskId = TaskId;
        info.Reason = txtReason.Text;
        info.SetTime = DateTime.Now;
        info.point = Convert.ToDecimal(txtPoint.Text);
        info.Id = Guid.NewGuid();
        TaskReasons.Insert(info);
        SaveSorce();
        init();
        txtPoint.Text = "";
        txtReason.Text = "";
    }

    public void SaveSorce()
    {
        //存入数据库
        int TaskId = int.Parse(Request.QueryString["RootId"]);
        string Userid = Request.QueryString["UserID"];
        string where = "taskId=" + TaskId + " and Userid='" + Userid + "' ";
        List<TaskReasonInfo> list = Yipusoft.Task.BLL.TaskReasons.GetList(where);
        decimal score = 0;
        string Description = "";
        for (int i = 0; i < list.Count; i++)
        {
            score += list[i].point;
            Description += "<br/>" + (i + 1) + "、" + list[i].Reason + "&nbsp&nbsp&nbsp&nbsp扣分：" + list[i].point;
        }
        TaskInfo root = Task.GetTask(int.Parse(Request.QueryString["RootId"]));
        TaskUserInfo user = TaskUser.GetTaskUser(int.Parse(Request.QueryString["RootId"]), Request.QueryString["UserID"]);
        //根据完成百分比给出应给分数。
        decimal TotolScore = Convert.ToDecimal(root.InitScore * user.Progress / 100);
        user.Score = TotolScore - score;

        user.Evaluated = true;
        user.Description = Description;
        TaskUser.Update(user);

    }
    protected void BtnBreak_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(hidDate.Value.Trim()))
        {
            Response.Redirect("TaskEvaluates.aspx?Year=" + DateTime.Parse(hidDate.Value).Year + "&Month=" + DateTime.Parse(hidDate.Value).Month);

        }
    }
    protected void gvReason_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label ID = (Label)e.Row.FindControl("ID");
            ID.Text = (e.Row.RowIndex + 1).ToString();
            //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色 
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#F5F5F5',this.style.fontWeight='';");
            //当鼠标离开的时候 将背景颜色还原的以前的颜色 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");

        }
    }
    protected void gvReason_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            Guid Id = new Guid(e.CommandArgument.ToString());
            if (TaskReasons.Delete(Id))
            {
                SaveSorce();
                init();
            }
        }
    }
}
